
/**
 * 获取 LoalStorage
 * @param key key
 * @returns 返回 T 或者 null
 * @example getItem<object>('user')
 */
export const getItem = <T>(key: string) => {
  const data = window.localStorage.getItem(key)
  if (!data) return null

  // 防止转换报错
  try {
    return JSON.parse(data) as T
  } catch (err) {
    return null
  }
}

/**
 * 设置 LocalStorage
 * @param key key
 * @param value value
 * @example setItem('user', { name: '张三', age: 12 })
 */
export const setItem = (key: string, value: object | string | null) => {
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  window.localStorage.setItem(key, value)
}

/**
 * 移除 LocalStorage
 * @param key 需要移除的 key
 * @example removeItem('user')
 */
export const removeItem = (key: string) => {
  window.localStorage.removeItem(key)
}
